#
# statistical operations in R
#
# this module should not use PyQt
#

import rpy
from rpy import r

import catcher

def dictSummary(h):
    """ show a summary of data in a dictionary """
    c=catcher.Catcher()
    rpy.set_rpy_output(catcher.catcher)
    rpy.set_default_mode(rpy.NO_CONVERSION)
    dData=rpy.r.data_frame(h)
    summary=rpy.r.summary(dData)
    rpy.set_default_mode(rpy.BASIC_CONVERSION)

    rpy.r.print_(summary)
    s = c.getText()
    c.reset()
    return s

def hist(data,xlab,main):
    """ plot a histogram """
    rpy.r.hist(data,main=main,xlab=xlab)


def xyplot(xdata,ydata,main,type='p'):
    """ do an xy plot of two variables """
    if len(ydata) == 1:
        rpy.r.plot(xdata.values()[0],ydata.values()[0],
                   xlab=xdata.keys()[0],ylab=ydata.keys()[0],
                   main=main,type=type)
    else:
        rpy.set_default_mode(rpy.NO_CONVERSION)
        rpy.r.matplot(xdata.values()[0],rpy.r.data_frame(ydata),
                  xlab=str(xdata.keys()[0]),
                  ylab=','.join(ydata.keys()))
        rpy.set_default_mode(rpy.BASIC_CONVERSION)
        

def splom(hashData,main):
    rpy.r.pairs(hashData,main=main)


def glm(x,yy,family):
    """ fit a GLM... """

    # construct the formula:
    rhs = "+".join(yy.keys())
    formula = x.keys()[0]+"~"+rhs
    # augment the data matrix with the response variable:
    yy[x.keys()[0]] = x.values()[0]

    rpy.set_default_mode(rpy.NO_CONVERSION)
    r('par(mfrow=c(2,2))')
    model=r.glm(r(formula),data=r.data_frame(yy),family=family)

    c=catcher.Catcher()
    rpy.set_rpy_output(catcher.catcher)
    summary=rpy.r.summary(model)
    # make the call component into something less awful:
    names = r.names(summary)
    rpy.set_default_mode(rpy.BASIC_CONVERSION)
    for i in range(r.length(summary)):
        if names[i]=='call':
            summary[i] = 'linear model: '+formula
    rpy.r.print_(summary)
    s = c.getText()
    c.reset()    
    r.plot( model)
    r('par(mfrow=c(1,1))')
    return s
    
if __name__=="__main__":


    x = {'x':[1,2,3,4,5,6,7]}
    data = {
        'a': [1, 2.3, 3.8, 4.2, 5.8, 6.1, 7.2],
        'c': [8.2, 7.8, 6.1, 5.2, 4, 3.2, 2],
        'b': [7, 6, 7, 6, 5, 5, 6]
        }
    glm(x,data,'Normal')
    from time import sleep
    sleep(4)
    raise ValueError

    hData={'a': range(10), 'b': [1,0,2,9,3,8,4,7,5,6]}
    print dictSummary(hData)
    from time import sleep

    hist(hData['b'],'b','some more data')
    sleep(2)

    xyplot({'a':hData['a']},{'b':hData['b']},"Some data","l")

    sleep(4)
    
